// pages/todos/todos.js
Page({
  data: {
    // 文本框数据模型
    input: '',
    // 任务框清单数据模型
    todos: [
      {id: '1', name: 'Learning HTML', completed: false},
      {id: '2',  name: 'Learning JavaScript', completed: true },
      {id: '3',  name: 'Learning HTML', completed: false },
    ],
    leftCount: 2,
    allCompleted: false,
  },
  // 实现点击添加思路一：
  // 1.先获取点击时候输入的数据
  // 2.将对应的数据添加到对应的数组中
  addTodoHandler: function(){
    // 当按钮添加点击事件发生时，添加函数
    // console.log('plus touched...');
    // 由于小程序的数据绑定是单向的，必须要给文本框注册函数
    // console.log(this.data.input);
    // 输入值的校验
    if(!this.data.input) return;
    var id = 0;
    this.data.todos.forEach((item,index) => {
      if(index == this.data.todos.length -1){
        id = item.id;
      }
    });
    // console.log('id:', id); //3
    id +=1;
    var todos = this.data.todos.push({
      id: id,
      name: this.data.input,
      completed: false
    });
    // 必须显式的通过setData改变数据这样界面才会得到变化
    this.setData({
      todos: todos,
      leftCount: this.data.leftCount +1,
      input: ''
    });
  },
  inputChangeHandler: function(e){
    // console.log('input changed');
    // console.log(e.detail.value);
    this.setData({
      input: e.detail.value
    });
  },
  toggleHandler: function(){
    // 切换当前点中的item的状态
    // console.log(e.currentTarget);
    var item = this.data.todos[e.currentTarget.dataset.index];;
    item.completed = !item.completed;
    var leftCount = this.data.leftCount + (item.completed ? -1 : 1);
    this.setData({
      todos: this.data.todos,
      leftCount: leftCount,
    });
  },
  // 删除触发的按钮
  // 注意冒泡的处理
  removeHandler: function(e){
    var todos = this.data.todos;
    // item就是移除掉的元素
    var item = todos.splice(e.currentTarget.dataset.index, 1);
    // 重新赋值
    this.setData({
      todos: todos,
      leftCount: (item.completed) ? leftCount : leftCount-1,
    });
  },
  toggleAllHandler: function(){
    // this在这里永远指向当前页面对象
    var todos = this.data.todos;
    this.data.allCompleted = !this.data.allCompleted;
    var that = this.data.allCompleted;
    todos.forEach(function( item){
      item.completed = that;
    });
    // 重新赋值
    this.setData({
      todos: todos,
      leftCount: this.data.allCompleted ? 0 : this.data.todos.length,
    });
  },
  clearHandler: function(){
    var todos = [];
    // this.data.forEach(function( item ){
    //   if(!item.completed){
    //     todos.push(item);
    //   }
    // });
    todos = this.data.todos.filter(function(item){
      return !item.completed;
    });
    // 重新赋值
    this.setData({
      todos: todos,
      leftCount: this.data.todos.length,
    });
  },
})